package com.qf.listener;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.constant.RabbitMQConstants;
import com.qf.model.StandardSubmit;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 监听 rabbitMQ 中   sms_send_log_topic
 * @author dell
 * @version V1.0
 * @Date 2022/6/9 15:03:58
 */
@Component
@Slf4j
public class LogListener {

    //Elasticsearch 的客户端
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Value("${log-index}")
    private String logIndex;

    @Autowired
    private ObjectMapper objectMapper;

    @RabbitListener(queues = RabbitMQConstants.TOPIC_SMS_SEND_LOG)
    public void receiverSmsSendLog(Message message, Channel channel, StandardSubmit standardSubmit){


        try {
            log.info("ES 开始 接收日志  ");

            IndexRequest request = new IndexRequest(logIndex);
            // 主键 id
            request.id(standardSubmit.getSequenceId());

            // 写入uuid 做为 msgid
            //standardSubmit.setMsgid(UUID.randomUUID().toString());

            // 文档
            request.source(objectMapper.writeValueAsString(standardSubmit), XContentType.JSON);
            // 执行保存
            IndexResponse index = restHighLevelClient.index(request, RequestOptions.DEFAULT);
            if (index.getResult().toString().equalsIgnoreCase("created")
                    || index.getResult().toString().equalsIgnoreCase("updated")) {
                //成功
                log.info("[搜索模块] 添加日志成功");
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

            }else {
                //重新发送
                log.error("[搜索模块] 添加日志失败");
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false,true);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
